﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Volusion.Automation.WebApi
{
    public static class ProjectFileProvider
    {
        public static string CreateProjectFile(string location, Version version, string rootNamespace, string assemblyName, IEnumerable<string> assembilies = null, IEnumerable<string> fileIncludes = null)
        {
            location = location.Replace("\\", "/").TrimEnd(new char[] { '/' });
            string RandId1 = Guid.NewGuid().ToString();
            string RandId2 = Guid.NewGuid().ToString();
            string RandId3 = Guid.NewGuid().ToString();
            string FlavorGuid = Guid.NewGuid().ToString();
            string UniqueIdentifier = Guid.NewGuid().ToString();

            string assemblyReferences = string.Empty;
            string fileReferences = string.Empty;

            if (assembilies != null)
                foreach (string s in assembilies)
                    assemblyReferences += "\t<Reference Include=\"" + s + "\" />\n";
            if (fileIncludes != null)
                foreach (string s in fileIncludes)
                {
                    string loc = "";
                    string[] split = s.Replace("\\", "/").Split('/');
                    for (int i = 0; i < split.Length - 1;i++ )
                        loc += split[i] + "/";

                    split = s.Replace("\\", "/").Split('/');
                    //foreach (string v in s.Replace("\\", "/").Split('/'))
                    //    if (!v.Contains('.'))
                    //        loc += v + "/";

                    if (!System.IO.Directory.Exists(loc))
                        System.IO.Directory.CreateDirectory(loc);

                    fileReferences += "\t<Compile Include=\"" + s + "\" />\n";
                }

            System.Resources.ResourceReader reader = 
                new System.Resources.ResourceReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Volusion.Automation.WebApi.Resources.resources"));
            string x = string.Empty;
            byte[] resourceData = null;
            reader.GetResourceData("ProjectFileTemplate", out x, out resourceData);
            string template = System.Text.Encoding.UTF8.GetString(resourceData);

            if (System.IO.File.Exists(location + "/Project.csproj"))
            {
                throw new Exception("Project file already exists at location: " + location + "/Project.csproj");
            }
            else
            {
                if (!System.IO.Directory.Exists(location))
                    System.IO.Directory.CreateDirectory(location);
                System.IO.File.WriteAllText(location + "/Project.csproj",
                    template
                    .Replace("{RandId1}", RandId1)
                    .Replace("{RandId2}", RandId2)
                    .Replace("{RandId3}", RandId3)
                    .Replace("{FlavorGuid}", FlavorGuid)
                    .Replace("{AssemblyReferences}", assemblyReferences)
                    .Replace("{FileIncludes}", fileReferences)
                    .Replace("{Version}", version.Major.ToString() + "." + version.Minor.ToString())
                    .Replace("{RootNamespace}", rootNamespace)
                    .Replace("{AssemblyName}", assemblyName)
                    .Replace("{UniqueIdentifier}", UniqueIdentifier));
                return location + "/Project.csproj";
            }
        }

        public enum TestProjectType
        {
            Unit,
            Acceptance,
            Integration
        }

        public static void CreateTestProject(string fullyQualifiedSolutionFileName, string projectName, TestProjectType testProjectType)
        {
            Type vsType = Type.GetTypeFromProgID("VisualStudio.DTE.9.0");
            Object vs = System.Activator.CreateInstance(vsType, true);
            EnvDTE80.DTE2 dte8Obj = (EnvDTE80.DTE2)vs;
            
            EnvDTE80.Solution2 vhaSolution = (EnvDTE80.Solution2)dte8Obj.Solution;
            vhaSolution.Create("C:/AutoGeneratedClasses/", "MyNewSolution");
            return;
           // vhaSolution.Open(fullyQualifiedSolutionFileName);

            //TODO: Externalize company name 
            string cmpnyName = "Vha";
            string testProjectName = String.Format("{0}.{1}.{2}{3}", cmpnyName, projectName, testProjectType.ToString(), "Test");
            string testTemplateLocation = vhaSolution.GetProjectTemplate("TestProject.zip", "CSharp");
            FileInfo rootSolutionFolder = new FileInfo(fullyQualifiedSolutionFileName);

            //TODO: Externalize test directory name 
            string testDirName = String.Format("C:/AutoGeneratedClasses/");

            if (!Directory.Exists(testDirName))
            {
                //may throw an exception if the dir can't be created... 
                Directory.CreateDirectory(testDirName);
            }


            EnvDTE.Project vhaTestProj = vhaSolution.AddFromTemplate(testTemplateLocation, testDirName, testProjectName + ".csproj", false);
            vhaTestProj.Save(String.Format("{0}\\{1}.csproj", testDirName, testProjectName));



        } 

    }
}
